package com.example.bilibili_fake.ui.home

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.LazyHeaders
import com.example.bilibili_fake.R
import com.example.bilibili_fake.data.model.Archive

class VideoAdapter(private val videos: List<Archive>) :
    RecyclerView.Adapter<VideoAdapter.VideoViewHolder>() {

    class VideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val titleText: TextView = view.findViewById(R.id.titleText)
        val authorText: TextView = view.findViewById(R.id.authorText)
        val coverImage: ImageView = view.findViewById(R.id.coverImage)
        val viewCountText: TextView = view.findViewById(R.id.viewCountText)
        val likeCountText: TextView = view.findViewById(R.id.likeCountText)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_video, parent, false)
        return VideoViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        val video = videos[position]
        holder.titleText.text = video.title
        holder.authorText.text = video.owner.name
        holder.viewCountText.text = formatCount(video.stat.view)
        holder.likeCountText.text = formatCount(video.stat.like)

        // 为 Glide 添加 User-Agent 头部，以避免某些图片服务器的访问限制
        val glideUrl = GlideUrl(
            video.pic, LazyHeaders.Builder()
                .addHeader(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
                )
                .build()
        )

        Glide.with(holder.coverImage.context)
            .load(glideUrl)
            .placeholder(R.drawable.ic_launcher_foreground)
            .centerCrop()
            .into(holder.coverImage)
    }

    override fun getItemCount() = videos.size

    private fun formatCount(count: Int): String {
        return when {
            count >= 10000 -> "${count / 10000}万"
            count >= 1000 -> "${count / 1000}千"
            else -> count.toString()
        }
    }
}